<template>
  <div class="song-audio">
    <audio id="player" :src="url"
        ref="musicaudio"
        controls="controls"
        preload="true"
        @canplay="canplay"
        @ended="ended"
        @timeupdate="timeupdate"
    >

    </audio>
  </div>
</template>

<script>
import { mapState ,mapMutations} from 'vuex';
export default {
  watch:{
    isPlay(){
      this.tooglePlay()
    },
    Volume(){
      this.$refs.musicaudio.volume = this.Volume
    }
  },
  computed:{
    ...mapState('music',['url','isPlay','Volume','AutoNext'])
  },
    methods:{
      ...mapMutations('music',['changeIsplay','getUrl','getCurTime','getduration','changAutoNext']),
        canplay(){
          this.$nextTick(()=>{
            const res = this.$refs.musicaudio.play()
            if (res !== undefined){
              res.then(_ => {
                this.$refs.musicaudio.play()
                     // Autoplay started! 这种情况可以自动播放（非谷歌的其他浏览器：edge、360）
              }).catch(error => {
                        //  Autoplay was prevented.谷歌和火狐就会阻止播放，可以显示一个PLAY按钮提示用户点击后进行播放
                  this.$refs.musicaudio.pause()
              });
            } 
          })
        },
        ended(){
          this.changeIsplay(false)
          this.getCurTime(0)
          this.changAutoNext(!this.AutoNext)
        },
        tooglePlay(){
          if(this.isPlay){
            this.$nextTick(()=>{
              this.$refs.musicaudio.play()
            })
          }
          else{
            this.$nextTick(()=>{
              this.$refs.musicaudio.pause()
            })
          }
        },
        timeupdate(){
          this.getCurTime(this.$refs.musicaudio.currentTime)
          this.getduration(this.$refs.musicaudio.duration)
        },
    }
}
</script>

<style scoped>

</style>